import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

// 通过循环生成的动态路由
const dynamicRoutes = []

// 公共路由 - 首页和404页面
const publicRoutes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: {
      title: '首页',
      keepAlive: true
    }
  },
  {
    path: '/split-screen',
    name: 'splitScreen',
    component: () => import('../components/layout/SplitScreen.vue'),
    meta: {
      title: '分屏模式',
      keepAlive: false
    }
  },
  {
    path: '/menu/:id',
    name: 'menu-item',
    component: () => import('../views/MenuView.vue'),
    meta: { noUrl: true },
    props: true,
    beforeEnter: async (to, from, next) => {
      try {
        const menuId = to.params.id
        const { useMenuStore } = await import('../stores/menuStore')
        const menuStore = useMenuStore()
        const menuItem = menuStore.getMenuItemById(menuId)

        if (menuItem) {
          to.meta = {
            ...to.meta,
            menuId: menuItem.id,
            title: menuItem.name,
            showIndex: menuItem.showIndex || '',
            backImage: menuItem.backImage || ''
          }
        }

        next()
      } catch (error) {
        console.error('Failed to load menu store:', error)
        next()
      }
    }
  },
  {
    path: '/404',
    name: 'notFound',
    component: () => import('../views/NotFound.vue'),
    meta: {
      title: '页面不存在'
    }
  }
]

// 创建路由实例，包含所有公共路由
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [...publicRoutes]
})

// 动态路由设置函数
export async function setupDynamicRoutes() {

  try {
    console.log('开始设置动态路由...')
    const { useMenuStore } = await import('../stores/menuStore')
    const menuStore = useMenuStore()

    // 清空之前的动态路由
    dynamicRoutes.length = 0

    // 生成新的动态路由
    generateRoutes(menuStore.menuData)

    // 添加动态路由
    dynamicRoutes.forEach(route => {
      if (!router.hasRoute(route.name)) {
        router.addRoute(route)
        console.log(`注册路由: ${route.path} (${route.name})`)
      }
    })

    // 最后添加通配符路由，确保它总是在最后
    if (router.hasRoute('catchAll')) {
      router.removeRoute('catchAll')
    }

    router.addRoute({
      path: '/:pathMatch(.*)*',
      name: 'catchAll',
      redirect: '/404'
    })

    console.log('动态路由设置完成，当前路由数量:', router.getRoutes().length)

    // 如果当前页面是 404，但实际上可能有对应的路由，尝试重新导航
    const currentRoute = router.currentRoute.value
    if (currentRoute.name === 'notFound' || currentRoute.name === 'catchAll') {
      const targetPath = currentRoute.fullPath
      router.replace(targetPath)
    }
  } catch (error) {
    console.error('设置动态路由失败:', error)
  }
}


// 递归生成路由
function generateRoutes(menus, parentName = '') {

  menus.forEach(menu => {
    // 如果有url则是菜单项，添加到路由
    if (menu.name && menu.url && !menu.url.startsWith('http')) {
      // 构建路由路径，去除可能的.vue后缀和多余的/
      let routePath = `/${menu.url.replace(/\.vue$/, '').replace(/^\/+/, '')}`

      // 对微前端应用，使用特殊的路由路径
      if (menu.viewType === 'W') {
        routePath = `/micro/${menu.id}`
      }

      // 添加到动态路由
      dynamicRoutes.push({
        path: routePath,
        name: `menu-${menu.id}`,
        component: () => import('../views/MenuView.vue'),
        meta: {
          title: menu.name,
          keepAlive: true,
          menuId: menu.id,
          parentName: parentName || menu.name,
          url: menu.url,
          viewType: menu.viewType || 'C',
          appEntry: menu.appEntry || '',
          appCode: menu.appCode || ''
        }
      })
    }

    // 递归处理子菜单
    if (menu.leafNodes && menu.leafNodes.length > 0) {
      generateRoutes(menu.leafNodes, menu.name)
    }
  })
}

// 全局导航守卫
router.beforeEach((to, from, next) => {
  // 确认动态路由已加载
  if (dynamicRoutes.length === 0 && to.name !== 'home' && to.name !== 'notFound') {
    console.log('检测到未加载动态路由，正在重新加载...')
    setupDynamicRoutes().then(() => {
      // 重新导航到目标路由
      next({ path: to.fullPath, replace: true })
    }).catch(() => {
      next()
    })
  } else {
    next()
  }
})

export default router
